//
//  CYCommonReleaseTVC.m
//  CreditAddressBook
//
//  Created by LE on 16/1/6.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYCommonReleaseTVC.h"
#import "BEMCheckBox.h"
#import "LEUnitView+LE.h"
#import "CYCreditTool.h"
#import "UIInfomationView.h"
#import "MTCityViewController.h"
#import "CYNavigationVController.h"
#import "CYNetworkCollectRecord.h"
#import "CYLoginHttpTool.h"
#import "CYJumpsTool.h"
#import "MBProgressHUD+MJ.h"
#import "MJExtension.h"
#import "AddressView.h"
#import "CYPersonReleaseVC.h"
#import "CYTool.h"

@interface CYCommonReleaseTVC ()<BEMCheckBoxDelegate,UITextFieldDelegate>


@property (strong, nonatomic) NSString *areaValue;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *idCardTF;
@property (weak, nonatomic) IBOutlet UITextField *titleTF;
@property (weak, nonatomic) IBOutlet UITextField *areaText;
@property (weak, nonatomic) IBOutlet UITextView *descriptionTV;
@property (weak, nonatomic) IBOutlet UIView *photoUploadView;
@property (weak, nonatomic) IBOutlet BEMCheckBox *manCheckBox;
@property (weak, nonatomic) IBOutlet BEMCheckBox *femaleCheckBox;
@property (nonatomic, strong) UIToolbar *toolBar;
@property (weak, nonatomic) IBOutlet UITextField *QQTF;


@property(nonatomic, strong) NSMutableArray *imageUrls;
@property(nonatomic, strong) NSString *selectedCity;
@property(nonatomic, strong) NSString *selectedDistrict;
@property(nonatomic, strong) NSString *selectedProvince;
@property(nonatomic, strong) BEMCheckBox *selectedCheckBox;
@property(nonatomic, assign) CYSex selectedSex;
@property (nonatomic, strong) AddressView *addressView;
@end

@implementation CYCommonReleaseTVC

- (NSMutableArray *)imageUrls {
    if (!_imageUrls) {
        _imageUrls = [NSMutableArray array];
    }
    return _imageUrls;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     
     _nameTF.delegate = self;
     _phoneTF.delegate = self;
     _titleTF.delegate = self;
     _idCardTF.delegate = self;
     _areaText.delegate = self;
     _QQTF.delegate = self;
     
    [self setupAttribute];
    [self setupItme];
    [self setupUploadView];
    [self initCheckBox];
    self.addressView = [[AddressView alloc] init];
    self.areaText.inputView = self.addressView;
    self.areaText.inputAccessoryView = self.toolBar;

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
     //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
     [_QQTF resignFirstResponder];
     [_nameTF resignFirstResponder];
     [_phoneTF resignFirstResponder];
     [_idCardTF resignFirstResponder];
     [_areaText resignFirstResponder];
     [_titleTF resignFirstResponder];
     
     return YES;
     
}

- (UIToolbar *)toolBar{
    if (_toolBar == nil) {
        self.toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44)];
        _toolBar.barTintColor= CYColor(95, 200, 100, 1);
        UIBarButtonItem *item1=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        UIBarButtonItem *item2=[[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(click)];
        _toolBar.items = @[item1, item2];
    }
    return _toolBar;
}

- (void)click {
    if (_areaText.isFirstResponder) {
        [_areaText resignFirstResponder];
        self.areaText.text = [NSString stringWithFormat:@"%@-%@-%@",self.addressView.province,self.addressView.city,self.addressView.area];
//            NSLog(@"text = %@",_areaText);
            _selectedCity = self.addressView.city;
            _selectedProvince = self.addressView.province;
            _selectedDistrict = self.addressView.area;
    }
    if([_areaText.text  isEqual: @"(null)-(null)-(null)"]) {
        NSString *p = @"北京市";
        NSString *c = @"北京辖区";
        NSString *a = @"东城区";
        _areaText.text = [NSString stringWithFormat:@"%@-%@-%@",p,c,a];
        _selectedCity = c;
        _selectedProvince = p;
        _selectedDistrict = a;
    }
}

- (void)setupAttribute {
    self.descriptionTV.layer.borderColor = [UIColor grayColor].CGColor;
    self.descriptionTV.layer.borderWidth = .5f;
}

- (void)setupItme {
    UIBarButtonItem *submit = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(submitClick)];
    self.navigationItem.rightBarButtonItem = submit;
}

- (void)submitClick {
     if (_phoneTF.text.length>0) {
          BOOL a = [CYTool isphoneNumber:_phoneTF.text];
          if (a) {
               //是
               
               
          }else{
               //不是
               CYAlertView(@"请输入正确的手机号");
               return;
               
          }

     }
     
     if (_idCardTF.text.length>0) {
          BOOL b = [CYTool isidcard:_idCardTF.text];
          if (b) {
               //是
               
          }else{
               //不是
               CYAlertView(@"请输入正确的身份证号");
               return;
               
          }
     }
     
    NSMutableDictionary *param = [self paramDic];
    if (param) {
        [MBProgressHUD showMessage:nil toView:self.view];
        [CYCreditTool addNetworkCollectRecordWithParams:param success:^(NSString *message) {
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            [MBProgressHUD showMessage:message toView:self.view];
            [self.navigationController popViewControllerAnimated:YES];
        } failure:^(NSString *message, BOOL isLogin) {
            [MBProgressHUD hideHUDForView:self.view animated:NO];
            if (!isLogin) {
                NSArray *controllers = self.navigationController.viewControllers;
                NSUInteger index = [controllers indexOfObject:self];
                UIViewController *controller = self.navigationController.viewControllers[index - 2];
                [self.navigationController popToViewController:controller animated:NO];
                [CYLoginHttpTool logoutWithController:self];
            } else {
                [MBProgressHUD showError:message];
            }
        }];
    }
}
- (NSMutableDictionary *)paramDic {
    CYUser *user = [CYLoginHttpTool userData].user;
    if (user) {
        CYNetworkCollectRecord *record = [CYNetworkCollectRecord new];
        if (self.nameTF.text && !self.nameTF.text.isEmpty) {
            record.name = self.nameTF.text;
        } else {
            [MBProgressHUD showError:@"请输入姓名"];
            return nil;
        }
        if (self.phoneTF.text && !self.phoneTF.text.isEmpty) {
            record.phone = self.phoneTF.text;
        }
        if (self.idCardTF.text && !self.idCardTF.text.isEmpty) {
            record.certificateNo = self.idCardTF.text;
        }
        record.sex = @(self.selectedSex);
        if (self.selectedProvince && !self.selectedProvince.isEmpty) {
            record.province = self.selectedProvince;
            record.city = self.selectedCity;
            record.district = self.selectedDistrict;
            
        } else {
            [MBProgressHUD showError:@"请选择违约人所在地区"];
            return nil;
        }
        if (self.titleTF.text && !self.titleTF.text.isEmpty) {
            record.title = self.titleTF.text;
        } else {
            [MBProgressHUD showError:@"请输入标题"];
            return nil;
        }
        if (self.descriptionTV.text && !self.descriptionTV.text.isEmpty) {
            record.defaultContent = self.descriptionTV.text;
        } else {
            [MBProgressHUD showError:@"请输入违约详情"];
            return nil;
        }
        if (self.imageUrls.count) {
            record.picAddress = self.imageUrls;
        } else {
            [MBProgressHUD showError:@"请上传证据照片"];
            return nil;
        }
        NSMutableDictionary *param = record.keyValues;
        param[@"userId"] = user.userId;
        param[@"token"] = user.token;
        if (_QQTF.text&&_QQTF.text.length) {
            param[@"qq"] = _QQTF.text;
        }
        return param;
    } else {
        [CYJumpsTool jumpToLogin:self];
    }
    return nil;
}

- (void)setupUploadView {
    CYWeakObject(wself, self);
    [LEUnitView imageScrollView:self.photoUploadView controller:self block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
        [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
            [wself.imageUrls addObject:imageUrl];
            cell.ratio = 1;
        } failure:^(NSError *error) {
            //删除
            [unitView deleteLastCell];
        } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            CGFloat a = totalBytesWritten;
            CGFloat b = totalBytesExpectedToWrite;
            cell.ratio = a/b - .01;
        }];
    } cellClick:^(LEUnitView *unitView, LEUnitCell *cell) {
//        [UIInfomationView showAlertViewWithTitle:@"确定删除？" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex) {
//            if (buttonIndex == 1) {
//                [unitView deleteCell:cell];
//            }
//        }];
    }];
}
- (IBAction)selectCityBtn:(UIButton *)sender {
    
//    MTCityViewController *city = [[MTCityViewController alloc] init];
//    CYNavigationVController *nav = [[CYNavigationVController alloc] initWithRootViewController:city];
//    nav.modalPresentationStyle = UIModalPresentationFormSheet;
//    CYWeakObject(weakself, self);
//    [city selectedCity:^(NSString *city) {
//        weakself.selectedCity = city;
//        [sender setTitle:city forState:UIControlStateNormal];
//    }];
//    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return .1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

#pragma mark - BEMCheckBoxDelegate
- (void)initCheckBox {
    self.manCheckBox.onAnimationType = BEMAnimationTypeBounce;
    self.manCheckBox.offAnimationType = BEMAnimationTypeBounce;
    self.femaleCheckBox.onAnimationType = BEMAnimationTypeBounce;
    self.femaleCheckBox.offAnimationType = BEMAnimationTypeBounce;
    self.femaleCheckBox.tag = CYSexMan;
    self.femaleCheckBox.tag = CYSexFemale;
    
    self.femaleCheckBox.delegate = self;
    self.manCheckBox.delegate = self;
    
    self.manCheckBox.on = YES;
    self.selectedCheckBox = self.manCheckBox;
    self.selectedSex = CYSexMan;
}

- (void)didTapCheckBox:(BEMCheckBox*)checkBox {
    if (checkBox.on) {
        self.selectedCheckBox.on = NO;
        self.selectedCheckBox = checkBox;
        self.selectedSex = checkBox.tag;
    } else {
        checkBox.on = YES;
    }
}
@end
